package ltd.smallwang.schedule_self_client

import android.content.Intent
import androidx.annotation.NonNull
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File

class MainActivity : FlutterActivity() {
    private val CHANNEL = "open_apk"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            CHANNEL
        ).setMethodCallHandler { call, result ->
            if (call.method == "openApk") {
                val path = call.argument<String>("path")
                if (path != null) {
                    val intent = Intent(Intent.ACTION_VIEW)
                    val file = File(path)
                    val uri = FileProvider.getUriForFile(
                        this,
                        "$packageName.provider", // 确保在AndroidManifest中定义了相应的FileProvider
                        file
                    )
                    intent.setDataAndType(uri, "application/vnd.android.package-archive")
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    startActivity(intent)
                    result.success(true)
                } else {
                    result.error("NO_PATH", "Path to APK is required.", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }
}